<template>
  <PageWrapper title="修改当前用户密码" content="修改成功后会自动退出当前登录！">
    <div class="py-8 bg-white flex flex-col justify-center items-center">
      <BasicForm @register="register" />
      <div class="flex justify-center">
        <a-button @click="resetFields"> 重置 </a-button>
        <a-button class="!ml-4" type="primary" @click="handleSubmit"> 确认 </a-button>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import { BasicForm, useForm } from '@/components/Form';
  import { modifyPassword } from '@/api/system/account'
  import { formSchema } from './pwd.data';
  import { useMessage } from '@/hooks/web/useMessage';
import { useUserStore } from '@/store/modules/user';
import { useRouter } from 'vue-router';
  const userStore = useUserStore();
  const { notification } = useMessage();
  export default defineComponent({
    name: 'ChangePassword',
    components: { BasicForm, PageWrapper },
    setup() {
      const [register, { validate, resetFields }] = useForm({
        size: 'large',
        labelWidth: 100,
        showActionButtonGroup: false,
        schemas: formSchema,
      });

      async function handleSubmit() {
        try {
          const values = await validate();
          const { passwordOld, passwordNew } = values;
          // 调用modifyPassword接口
          const res = await modifyPassword({ passwordOld, passwordNew });
          if (res.code !== 200) {
            notification.error({
                message: '修改失败！',
                description: res.message,
                duration: 3,
              });
            return;
          }else{
            // TODO 退出登录
            notification.success({
                message: '密码修改成功！',
                description: '密码修改成功！',
                duration: 3,
              });
              // 调用退出登录，清楚token
              // 2秒后退出
              setTimeout(async () => {
                await userStore.logout(true);
              }, 2000);   
              // userStore.logout();  
          }
          // TODO custom api
          console.log(passwordOld, passwordNew);
          // const { router } = useRouter();
          // router.push(pageEnum.BASE_LOGIN);
        } catch (error) {
          console.log(error);
        }
      }

      return { register, resetFields, handleSubmit };
    },
  });
</script>
